<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { onLoad } from '@dcloudio/uni-app'
import { makePhoneCall, navigateTo } from '@uni-helper/uni-promises'
import { get } from 'lodash-es'
import { getPaymentRecord } from '@/api/pay'
import type { PaymentRecordDto } from '@/api/pay/type'
import { SalaryStatusEnum } from '@/constant/enum'
import { getSalaryAli, getSalaryWechat } from '@/package-mine/api/pay'
import user from '@/composables/user'
import { shake, toast } from '@/utils/utils'
import { getUnsignedContactList } from '@/api/contract'
import { querySalaryCard } from '@/utils/salary-card'

export interface ExtraDataDto {
    id: number
    isCollectBankCardImg: number | string
    isCollectOpenBankAddress: number | string
    isCollectOpenBankCity: number | string
    isCollectOpenBankName: number | string
}

const eventChannel = ref()

const recordData = ref<PaymentRecordDto>({} as PaymentRecordDto)

// 是否只是纯展示，没有下面的按钮，有些其他页面跳过来只需要展示不能操作 传viewType=view
const isView = ref(false)
const isTipUp = ref(false)
// 开通银行卡时的额外信息 需要传过来
const extraData = ref<ExtraDataDto>()

const id = ref(0)

const showNoRegisterPopup = ref(false)
const showPopup = ref(false)
const isEdition = ref(false)

// 微工卡领薪
const checked = ref(true)

async function onCloseTip() {
    isTipUp.value = false
}

function isAfter2024Dec1(date: string) {
    const targetDate = dayjs('2024-12-01')
    const inputDate = dayjs(date)
    return inputDate.isAfter(targetDate) || inputDate.isSame(targetDate)
}

async function onToAlipayRedBagRule() {
    uni.downloadFile({
        url: 'https://bullet-static.oss-cn-shanghai.aliyuncs.com/paywage-file/12%E6%9C%88%E6%94%AF%E4%BB%98%E5%AE%9D%E6%8F%90%E7%8E%B0%E5%8F%B0%E6%B4%BB%E5%8A%A8%E8%A7%84%E5%88%99.docx',
        success: (res) => {
            uni.openDocument({
                filePath: res.tempFilePath,
                success: (res) => {
                    console.log('打开文档成功', res)
                },
                fail: (err) => {
                    console.log('打开文档失败', err)
                },
            })
        },
    })
}

// 是否开通微工卡
const isOpenSalaryCard = computed(() => {
    return user.userInfo.value?.isOpenSalaryCard
})

async function getRecord(id: number) {
    const res = await getPaymentRecord({ id })
    recordData.value = res

    res.params.sign_time_in = res.params.sign_time_in ? res.params.sign_time_in.split(' ')[1] : ''
    res.params.sign_time_out = res.params.sign_time_out ? res.params.sign_time_out.split(' ')[1] : ''

    const age = await getCardAge(res.idCardNo)
    // 快速领薪
    isEdition.value = !!res.flagQuicklyGetSalary && age >= 45

    await hasNoContact()
}

/**
 * 判断是否无待签署合同
 *
 * @returns 返回 Promise，无待签署合同则 resolve(true)，有待签署合同则 reject(new Error('有合同未签署'))
 */
async function hasNoContact() {
    return new Promise(async (resolve, reject) => {
        const contactList = await getUnsignedContactList({
            companyId: recordData.value.companyId,
        })
        if (contactList.length) {
            uni.showModal({
                title: '温馨提示',
                content: `应劳务公司要求，需要您签署合同后领薪，您有${contactList.length}份合同待签署。请前往微信小程序签署。`,
            })
            reject(new Error('有合同未签署'))
        }
        else {
            resolve(true)
        }
    })
}

/**
 * 联系驻厂
 *
 * @returns 无返回值
 */
async function onContactResident() {
    const linkmanList = recordData.value?.params?.linkmanList || []

    const sheet = linkmanList.map((item) => {
        return `${item.linkman} ${item.phone}`
    })

    const result = await uni.showActionSheet({
        itemList: sheet,
    })

    await makePhoneCall({
        phoneNumber: linkmanList[result.tapIndex].phone,
    })
}

/**
 * 跳转到银行卡页面
 *
 * @param otherData 其他数据对象，默认为空对象
 * @returns 无返回值
 */
async function toBank(otherData: AnyObject = {}) {
    const event = await navigateTo({
        url: '/package-mine/pages/bank-card/bank-card',
    })
    event.eventChannel.emit('extraData', {
        extraData: {
            ...extraData.value,
            ...otherData,
            from: 'salary',
        },
    })
}

/**
 * 支付宝领取薪资
 *
 * @returns 无返回值，执行完会跳转到薪资状态页面
 */
async function onGetSalary() {
    shake(async () => {
        await getRecord(id.value)
        if (recordData.value.isShowPop) {
            toast('应劳务公司要求，需要您填写完银行卡号码。')
            toBank()
            return
        }
        if (extraData.value?.isCollectOpenBankName === 1 && !user.userInfo.value.openBankName) {
            toast('应劳务公司要求，需要您填写完开户行城市信息。')
            toBank()
            return
        }
        if (recordData.value?.params?.isNeedIdcardPhoto === 1 && !user.userInfo.value?.ownIdCardFront && !user.userInfo.value?.ownIdCardBack) {
            toast('未上传身份证照片，请在上传后在进行领取。')
            uni.navigateTo({
                url: '/package-mine/pages/card-info/card-info',
            })
            return
        }

        let data = {
            type: '',
            status: 0,
            message: '',
        }
        const res = getSalaryAli({
            id: recordData.value.id,
            phone: user.userInfo.value?.phone,
            detailOrderNo: recordData.value?.detailOrderNo,
        }).catch((err) => {
            data = {
                type: 'error',
                status: 3,
                message: err.msg,
            }
        })
        if (!data.type) {
            data = {
                type: 'success',
                status: 1,
                message: '',
            }
        }
        await wait(100)
        const event = await navigateTo({
            url: '/package-mine/pages/salary-status/salary-status',
            events: {
                refresh: () => {
                    getRecord(id.value)
                },
            },
        })
        event.eventChannel.emit('responseData', {
            ...data,
            id: recordData.value.id,
            phone: user.userInfo.value?.phone,
            detailOrderNo: recordData.value?.detailOrderNo,
            platform: 'alipay',
        })
    })
}

/**
 * 判断是否注册了微信/是否开通了微工卡
 *
 * @returns 返回一个Promise对象，无返回值
 */
async function isRegistryWechat() {
    return new Promise((resolve, reject) => {
        // 通过有没有openId来判断是否注册了微信
        if (!user.userInfo.value?.openId) {
            showNoRegisterPopup.value = true
            reject(false)
        }
        resolve(true)
    })
}

/**
 * 微信领薪到零钱
 *
 * @returns 无返回值，执行过程中可能进行页面跳转
 */
async function onGetWallet() {
    await isRegistryWechat()

    // 判断有没有合同
    await hasNoContact()
    const isSalary = uni.getStorageSync('isSalary')
    if (!isSalary) {
        // 上报埋点 等开通
        // reportEvent('salary', {
        //     'userid': user.userId,
        //     'age': getCardAge(this.data.detailsList.idCardNo),
        //     'salary_channel': '零钱'
        // })
        uni.setStorageSync('isSalary', true)
    }

    let hint = ''
    let url = '/package-mine/pages/bank-card/bank-card'
    console.log(extraData.value)

    if (recordData.value.isShowPop)
        hint = '应劳务公司要求，需要您填写完银行卡号码。'

    if (extraData.value?.isCollectOpenBankName === 1 && !user.userInfo.value.openBankName)
        hint = '应劳务公司要求，需要您填写完银行开户行信息。'

    if (extraData.value?.isCollectOpenBankCity === 1 && !user.userInfo.value.openBankCity)
        hint = '应劳务公司要求，需要您填写完开户行城市信息。'

    if (recordData.value.params.isNeedIdcardPhoto === 1 && !user.userInfo.value?.ownIdCardFront && !user.userInfo.value?.ownIdCardBack) {
        hint = '未上传身份证照片，请在上传后在进行领取。'
        url = '/package-mine/pages/card-info/card-info'
    }

    if (hint) {
        const res = await uni.showModal({
            title: '提示',
            content: hint,
        })
        if (res.confirm) {
            await navigateToNext(url)
            return
        }
        if (res.cancel)
            return
    }

    getPaid('WECHATPAY_ACCOUNT')
}

/**
 * 微信领薪到银行卡
 *
 * @returns 无返回值，执行过程中可能进行页面跳转
 */
async function onGetBank() {
    await isRegistryWechat()

    const idCardFront = !!user.userInfo.value?.ownIdCardFront

    if (recordData.value.params.isNeedIdcardPhoto === 1 && recordData.value.isShowPop === 1 && !idCardFront) {
        const event = await navigateTo({
            url: '/package-mine/pages/bank-id-card/bank-id-card',
        })
        event.eventChannel.emit('extraData', {
            extraData: {
                id: id.value,
                isShowCollectOpenBankAddress: recordData.value.isCollectOpenBankAddress,
                isCollectOpenBankCity: extraData.value?.isCollectOpenBankCity,
                isCollectOpenBankName: extraData.value?.isCollectOpenBankName,
            },
        })
        return
    }

    let toastContent = ''

    if (recordData.value.isShowPop)
        toastContent = '应劳务公司要求，需要您填写完银行卡号码。'
    else if (extraData.value?.isCollectOpenBankName === 1 && !user.userInfo.value.openBankName)
        toastContent = '应劳务公司要求，需要您填写完银行开户行信息。'
    else if (extraData.value?.isCollectBankCardImg === 1 && !user.userInfo.value?.bankCardImg)
        toastContent = '应劳务公司要求，需要您提交银行卡照片。'

    if (toastContent) {
        toast(toastContent)
        toBank({
            id: id.value,
            isShowCollectOpenBankAddress: recordData.value.isCollectOpenBankAddress,
        })
        return
    }

    const isSalary = uni.getStorageSync('isSalary')

    if (!isSalary) {
        // #ifdef MP-ALIPAY
        my.reportCustomEvent('104527945', {
            bizType: 'cloudappevent',
            age: getCardAge(recordData.value.idCardNo),
            salary_channel: '银行卡',
        })
        // #endif

        // 事件上报
        // #ifdef MP-WEIXIN
        // reportEvent('salary_card', {
        //     userid: user.userId,
        //     age: getCardAge(this.data.detailsList.idCardNo),
        //     salary_channel: '银行卡',
        // })
        // #endif
        uni.setStorageSync('isSalary', true)
    }

    try {
        const res = await querySalaryCard(recordData.value.companyId).catch((err) => {
            if (err)
                toast('请去微信小程序开通微工卡')
            else
                toast('劳务公司暂未开通微工卡服务')

            throw new Error('没开通微工卡')
            // err ? toast('请去微信端开通微工卡') : toast('劳务公司暂未开通微工卡服务')
        })
        if (!res?.isOpenSalaryCard) {
            toast('劳务公司暂未开通微工卡服务')
            return
        }
        await hasNoContact()
        getPaid('BANK_ACCOUNT')
    }
    catch (err) {
        console.log(1111, err)
    }
}

async function navigateToNext(url: string) {
    const event = await navigateTo({
        url,
    })
    event.eventChannel.emit('extraData', {
        id: id.value,
        isshowCollectOpenBankAddress: recordData.value.isCollectOpenBankAddress,
        ...extraData.value,
    })
}

/**
 * 提现
 * @param type 领薪的类型 'BANK_ACCOUNT' 领取到微工卡 'WECHATPAY_ACCOUNT' 领取到微信零钱
 * @returns 无返回值
 */
async function getPaid(type: string) {
    shake(async () => {
        if (recordData.value?.params?.isNeedIdcardPhoto === 1 && !user.userInfo.value.ownIdCardFront && !user.userInfo.value.ownIdCardBack) {
            const res = await uni.showModal({
                title: '提示',
                content: '未上传身份证照片，请在上传后在进行领取',
            })
            if (res.confirm) {
                uni.navigateTo({
                    url: '/package-mine/pages/card-info/card-info',
                })
                return
            }
            if (res.cancel)
                return
        }

        const data = {
            title: '',
            type: '',
            content: '',
            color: '#FF7E68',
            id: recordData.value.companyId,
            phone: recordData.value.params.linkmanList[0].phone,
            order: recordData.value?.detailOrderNo,
            payid: id.value,
            platform: 'wechat',
            status: 1, // 1 处理中 2 成功 3 失败
            transferScene: type,
        }

        const result = await getSalaryWechat({
            id: id.value,
            detailOrderNo: recordData.value?.detailOrderNo,
            transferScene: type || '',
        }).catch((err) => {
            data.title = '提现失败'
            data.status = 3
            data.type = 'error'
            data.content = err?.data?.msg || err?.msg || '网络错误，请稍后再试'
            data.color = '#FF7E68'
            toResult(data)
        })

        if (result && result.type === '转账失败') {
            data.title = '提现失败'
            data.status = 3
            data.type = 'error'
            data.content = result.msg
            toResult(data)
            return
        }
        else if (result && result.msg) {
            data.title = '提现中'
            data.type = 'success'
            data.status = 1
            data.content = result.msg
            data.color = '#04CD5A'
            toResult(data)
            return
        }
        data.title = '提现中'
        data.status = 1
        data.content = ''
        data.type = 'success'
        data.color = '#04CD5A'
        toResult(data)
    })
}

/**
 * 跳转到领薪结果页
 *
 * @param data 待转化的数据
 * @returns 无返回值
 */
async function toResult(data: AnyObject) {
    const event = await navigateTo({
        url: '/package-mine/pages/salary-status/salary-status',
        events: {
            refresh: () => {
                getRecord(id.value)
            },
        },
    })
    event.eventChannel.emit('responseData', data)
    event?.eventChannel.emit('phone', recordData.value?.params?.linkmanList || [])
}

function onCheckboxChange(ev: {
    detail: { value: boolean }
}) {
    checked.value = ev.detail.value
}

onLoad(async (options) => {
    isView.value = options?.viewType === 'view'
    if (options?.id) {
        id.value = options?.id
        await getRecord(id.value)
    }
})

onMounted(() => {
    if (isAfter2024Dec1(dayjs().format('YYYY-MM-DD')))
        isTipUp.value = true

    else
        isTipUp.value = false

    const instance = getCurrentInstance()
    eventChannel.value = get(instance, 'proxy.getOpenerEventChannel', new Function()).call(instance?.proxy)
    eventChannel.value.on('extraData', async (data: AnyObject) => {
        isView.value = data?.viewType === 'view'
        extraData.value = data as ExtraDataDto
        if (data.id) {
            id.value = data?.id
            await getRecord(data.id)
        }
    })
})
</script>

<template>
    <NavbarContainer nav-title="薪资详情" nav-color="#fff"
                     background-url="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager363631e9-06ab-476d-890f-a9978e34dd83.png">
        <view class="set-bg h-full">
            <view class="box-border px-30rpx">
                <view
                    class="mb-24rpx mt-40rpx box-border w-full flex flex-col gap-24rpx rounded-16rpx bg-#ffffff p-30rpx">
                    <view class="w-full flex items-center justify-between">
                        <view class="text-36rpx font-700">{{ recordData.serveCompanyName }}</view>
                        <view class="text-28rpx text-#ff7642">{{ SalaryStatusEnum[recordData.status] }}</view>
                    </view>
                    <view class="w-full flex items-center justify-between text-24rpx text-#9497b1">
                        <view class="text-#202536">流程单号: {{ recordData.detailOrderNo }}</view>
                        <view />
                    </view>
                    <view class="w-full flex items-center justify-between text-46rpx font-700">
                        <view class="">
                            {{ recordData.params?.sign_time_in ? recordData.params?.sign_time_in : '无记录' }}
                        </view>
                        <view class="">
                            {{ recordData.params?.sign_time_out ? recordData.params?.sign_time_out : '无记录' }}
                        </view>
                    </view>
                    <view class="w-full flex items-center justify-between text-24rpx text-#9497b1">
                        <view>签到</view>
                        <view>签退</view>
                    </view>
                    <view class="w-full flex items-center justify-between">
                        <view class="text-24rpx text-#9497b1">
                            工作时间：<span class="text-#202536">{{
                                recordData.workDate && dayjs(recordData.workDate).format('YYYY-MM-DD')
                            }}</span>
                        </view>
                        <view class="text-24rpx text-#9497b1">
                            发薪时间：<span class="text-#202536">{{
                                recordData.payTime && dayjs(recordData.payTime).format('YYYY-MM-DD')
                            }}</span>
                        </view>
                    </view>
                </view>
                <view class="box-border w-full rounded-16rpx bg-#ffffff pt-30rpx">
                    <view class="mb-20rpx box-border w-full flex items-center justify-between px-30rpx">
                        <view class="text-24rpx text-#202536">应发薪资：</view>
                        <view class="text-24rpx text-#ff7642 font-500">¥ {{ recordData.paymentAmount }}</view>
                    </view>
                    <view class="mb-20rpx box-border w-full flex items-center justify-between px-30rpx">
                        <view class="text-24rpx text-#202536">提现手续费：</view>
                        <view class="text-24rpx text-#ff7642 font-500">本次免费</view>
                    </view>
                    <view class="mb-20rpx box-border w-full flex items-center justify-between px-30rpx">
                        <view class="text-24rpx text-#202536">实发薪资：</view>
                        <view class="text-24rpx text-#ff7642 font-500">¥ {{ recordData.paymentAmount }}</view>
                    </view>
                    <view class="mb-20rpx box-border w-full flex items-center justify-between px-30rpx">
                        <view class="text-24rpx text-#202536">支付方式：</view>
                        <view class="text-24rpx font-500">
                            {{ recordData.payAccountFlag === 20001 ? '支付宝支付' : '微信支付' }}
                        </view>
                    </view>
                    <view v-if="recordData.params?.flagUserRemark"
                          class="mb-20rpx box-border w-full flex items-center justify-between px-30rpx">
                        <view class="text-24rpx text-#202536">发薪备注：</view>
                        <view class="text-24rpx text-#ff7642 font-500">{{ recordData.detailRemarks }}</view>
                    </view>
                    <view
                        class="box-border h-80rpx w-full flex items-center justify-center gap-20rpx rounded-b-16rpx bg-#fafafc px-30rpx"
                        @click="onContactResident">
                        <img class="h-24rpx w-24rpx" src="../../../static/images/telephone/telephone.png">
                        <span class="text-24rpx">联系驻厂</span>
                    </view>
                </view>
            </view>
            <view v-if="!isView && recordData.status !== 1" class="pos-fixed bottom-0 left-0 box-border w-full">
                <view v-if="isTipUp && recordData.payAccountFlag === 20001" class="mb-12px px-30rpx">
                    <view
                        class="flex items-center justify-between gap-20rpx rounded-25rpx bg-hex-202536 px-24rpx py-2px">
                        <view class="flex items-center justify-between gap-20rpx">
                            <view class="text-32rpx text-hex-ffffff" @click="onCloseTip">×</view>
                            <image
                                src="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager33d28d1a-caaf-42c5-81c1-a9ec7d9e3772.png"
                                class="h-100rpx w-100rpx" />
                            <view class="text-30rpx text-hex-ffffff line-height-none">
                                支付宝提现
                                <text class="text-hex-ff7642">10元</text>
                                以上得过年礼包
                            </view>
                        </view>
                        <view
                            class="h-44rpx w-80rpx flex flex-shrink-0 items-center justify-center rounded-25rpx bg-hex-ffffff text-24rpx text-hex-202536B3"
                            @click="onToAlipayRedBagRule">
                            规则
                        </view>
                    </view>
                </view>
                <view class="box-border w-full bg-#ffffff px-30rpx pt-10rpx pb-safe-20rpx">
                    <view
                        v-if="recordData.status === SalaryStatusEnum['待领薪'] || recordData.status === SalaryStatusEnum['领取失败']"
                        class="w-full pb-20rpx">
                        <view v-if="recordData.payAccountFlag === 20001"
                              class="box-border h-88rpx w-full flex items-center justify-center rounded-44rpx bg-orange text-32rpx text-#ffffff"
                              @click="onGetSalary">
                            领取到支付宝账户
                        </view>
                        <view v-else>
                            <view class="flex gap-16rpx">
                                <view
                                    class="h-88rpx flex flex-1 flex-col items-center justify-center border border-#DEE0E3 rounded-full border-solid text-center"
                                    @click="onGetBank">
                                    <view class="text-32rpx font-bold">微工卡提现</view>
                                    <view class="text-20rpx text-textgray font-bold">自定义提现账户</view>
                                </view>
                                <view
                                    class="set-button-bg relative h-88rpx flex flex-auto flex-col items-center justify-center rounded-full text-center text-white"
                                    @click="onGetWallet">
                                    <view class="text-32rpx font-bold">提现至微信零钱</view>
                                    <view class="text-20rpx font-bold">极速领薪 秒到账</view>
                                    <view
                                        class="absolute right-30rpx rounded-full rounded-lb-0 bg-#FDB114 px-16rpx py-4rpx text-24rpx text-white -top-20rpx">
                                        推荐
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <pop-up v-model:show="showNoRegisterPopup" title="领取薪资">
                        <view class="mt-30rpx text-center text-gray">
                            打开微信，顶部搜索
                            <text class="text-black font-bold">“子弹工作”</text>
                        </view>
                        <view class="text-center text-gray">注册领薪</view>
                        <image class="mx-auto mt-30rpx block h-327rpx w-530rpx"
                               src="../../assets/image/salary/wx-image-1.png" />
                    </pop-up>
                </view>
            </view>
            <view v-if="recordData.status === SalaryStatusEnum['已领薪']"
                  class="pos-fixed bottom-0 left-0 box-border w-full bg-#ffffff px-30rpx pt-10rpx pb-safe-20rpx">
                <!-- #ifdef MP-ALIPAY -->
                <view v-if="recordData.payAccountFlag === 10001" class="flex justify-between">
                    <view class="h-88rpx w-full rounded-full bg-lightgray text-center text-gray lh-88rpx">
                        提现成功 可打开微信查看
                    </view>
                </view>
                <!-- #endif -->
                <!-- #ifdef MP-WEIXIN -->
                <view v-if="recordData.payAccountFlag === 10001" class="flex justify-between">
                    <view class="h-88rpx w-full rounded-full bg-lightgray text-center text-gray lh-88rpx" />
                </view>
                <!-- #endif -->
            </view>
        </view>
    </NavbarContainer>
</template>

<style scoped>
.set-bg {
    background: linear-gradient(90deg, #3e5ff5 0%, #3b72f5 100%);
}

.set-button-bg {
    background: linear-gradient(-264deg, #FF8F34 3%, #FF363D 98%);
}
</style>

<route lang="json">
{
"style": {
"navigationBarTextStyle": "white",
"navigationBarTitleText": "薪资详情",
"mp-alipay": {
"transparentTitle": "always"
}
}
}
</route>
